package ru.javadevelop.homefinans.models;

import android.content.Context;
import com.neurospeech.wsclient.WSHelper;
import com.neurospeech.wsclient.WSObject;
import org.w3c.dom.*;
import ru.javadevelop.homefinans.common.DB;
import ru.javadevelop.homefinans.models.interfaces.IBaseRemoteDbEntity;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * http://t-menu.ru
 * User: navff
 * Date: 18.07.12
 * Time: 6:36
 */


public class Cost implements IBaseRemoteDbEntity{
    public String id;
    public String categoryId;
    public BigDecimal sum ;
    public Date date;
    public String username;


    public Cost (String id, BigDecimal sum, String categoryId, String username, Date date)
    {
        this.id = id;
        this.sum = sum;
        this.categoryId = categoryId;
        this.date = Calendar.getInstance().getTime();
        this.username = username;
        this.date = date;
    }

    public Cost()
    {}

    public String save() {
        boolean exists = this.id != null && DB.INSTANCE.executeSql(new DB.Handler<Boolean>() {
            @Override
            public Boolean  execute(Statement stmt) throws SQLException {
                ResultSet resultSet = stmt.getResultSet();
                return resultSet.next();
            }
        }, "SELECT * FROM costs WHERE id=?", this.id);
        // Если запись существовала, — обновляем её  (проверяется по id)
        // у вновь создаваемых записей id=0

        if  (exists)
        {
            DB.INSTANCE.executeSql("UPDATE costs SET sum_ = ?,  category_id = ?, username=? WHERE id = ?",
                                   this.sum,
                                   categoryId,
                                   username,
                                   this.id);
            return this.id;
        }
        else
        {
            // Если записи не существовало, — добавляем новую
            String newId = UUID.randomUUID().toString();
            DB.INSTANCE.executeSql("INSERT INTO costs (id, sum_, category_id, username, date_) VALUES(?,?,?,?,?)",
                                    newId, this.sum, categoryId, username, date);
            this.id = newId;
            return this.id;
        }
    }

    public void saveToRemoteDb() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void refreshFromRemoteDb() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public static ArrayList<Cost> getAll()
    {
        return DB.INSTANCE.executeSql(new DB.Handler<ArrayList<Cost>>() {
            @Override
            public ArrayList<Cost> execute(Statement stmt) throws SQLException {
                ArrayList<Cost> result = new ArrayList<Cost>();
                ResultSet resultSet = stmt.getResultSet();
                while (resultSet.next())
                {
                    result.add(new Cost(resultSet.getString(1),
                                        resultSet.getBigDecimal(2),
                                        resultSet.getString(3),
                                        resultSet.getString(4),
                                        resultSet.getDate(5))
                              );
                }
                return result;

            }
        }, "SELECT * FROM costs");
    }

    public static void deleteAll(String username)
    {
        DB.INSTANCE.executeSql("DELETE FROM costs WHERE username=?", username);
    }
}
